package controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import util.Log;

import model.UserAccount;

import db.UserAccountDAO;

public class FrontController extends HttpServlet{

	private static final long serialVersionUID = 1L;
	private static UserAccountDAO users = new UserAccountDAO();
	
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		if(request.getSession().getAttribute("user") != null){
			if(request.getParameter("logout") != null){
				logout(request, response);
			} else request.getRequestDispatcher("/WEB-INF/index.jsp").forward(request, response);
		} else {
			request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);
		}				
	}	
	
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {		
		String name = request.getParameter("login_username");
		String password = request.getParameter("login_password");		
		UserAccount user = users.find(name, password);
		if(user != null){		
			request.getSession().setAttribute("user", user);
			request.getRequestDispatcher("/WEB-INF/index.jsp").forward(request, response);
			Log.write(user.getUsername()+" Logged in");
		} else{			
			request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);
		}
	}

	private void logout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Log.write(((UserAccount)request.getSession().getAttribute("user")).getUsername()+" Logged out.");
		request.getSession().setAttribute("user", null);
		request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);
	}
}

